from flask import Blueprint, render_template, request, redirect, url_for, session, flash, jsonify, make_response
from models import UserModel, CardModel, db, TradeModel, DepositModel
from sqlalchemy import or_, func
import csv
from io import StringIO
import random
from datetime import datetime

admindeposit_dp=Blueprint('admindeposit',__name__,url_prefix='/admindeposit')

@admindeposit_dp.route('/admindeposit', methods=['GET', 'POST'])
def admindeposit():
    # 处理搜索和分页
    saving_name_search = request.args.get('savingNameSearch', '')
    descrip_search = request.args.get('descripSearch', '')
    page = request.args.get('page', 1, type=int)
    per_page = 10  # 每页显示10条记录

    # 构建查询 - 按savingID升序排列
    query = DepositModel.query.order_by(DepositModel.savingID.asc())

    if saving_name_search:
        query = query.filter(DepositModel.savingName.like(f'%{saving_name_search}%'))

    if descrip_search:
        query = query.filter(DepositModel.descrip.like(f'%{descrip_search}%'))

    # 分页
    deposits = query.paginate(page=page, per_page=per_page)

    # 处理表单提交（添加/编辑/删除）
    if request.method == 'POST':
        action = request.form.get('action')

        # 添加存款类型
        if action == 'add':
            saving_name = request.form.get('savingName')
            descrip = request.form.get('descrip')

            if not saving_name:
                flash('存款类型名称不能为空', 'danger')
            else:
                new_deposit = DepositModel(savingName=saving_name, descrip=descrip)
                db.session.add(new_deposit)
                db.session.commit()
                flash('存款类型添加成功', 'success')

        # 编辑存款类型
        elif action == 'edit':
            saving_id = request.form.get('savingID')
            saving_name = request.form.get('savingName')
            descrip = request.form.get('descrip')

            deposit = DepositModel.query.get(saving_id)
            if deposit:
                deposit.savingName = saving_name
                deposit.descrip = descrip
                db.session.commit()
                flash('存款类型更新成功', 'success')
            else:
                flash('找不到该存款类型', 'danger')

        # 删除存款类型
        elif action == 'delete':
            saving_id = request.form.get('savingID')
            deposit = DepositModel.query.get(saving_id)
            if deposit:
                # 检查是否有银行卡使用该存款类型
                card_count = CardModel.query.filter_by(savingID=saving_id).count()
                if card_count > 0:
                    flash('该存款类型已被银行卡使用，无法删除', 'danger')
                else:
                    db.session.delete(deposit)
                    db.session.commit()
                    flash('存款类型删除成功', 'success')
            else:
                flash('找不到该存款类型', 'danger')

        # 导出CSV - 也按savingID升序排列
        elif action == 'export_csv':
            # 使用相同的排序规则：按savingID升序
            deposits_all = DepositModel.query.order_by(DepositModel.savingID.asc()).all()

            # 创建CSV文件
            si = StringIO()
            cw = csv.writer(si)
            cw.writerow(['存款类型ID', '存款类型名称', '描述'])

            for deposit in deposits_all:
                cw.writerow([
                    deposit.savingID,
                    deposit.savingName,
                    deposit.descrip
                ])

            # 创建响应
            output = make_response(si.getvalue())
            output.headers["Content-Disposition"] = "attachment; filename=deposits_export.csv"
            output.headers["Content-type"] = "text/csv"
            return output

        return redirect(url_for('admindeposit.admindeposit',
                                savingNameSearch=saving_name_search,
                                descripSearch=descrip_search))

    return render_template('admin_main_deposit.html',
                           deposits=deposits,
                           savingNameSearch=saving_name_search,
                           descripSearch=descrip_search)